home *** CD-ROM | disk | FTP | other *** search
/ MacFormat 1995 January / macformat-020.iso / Shareware City / Developers / bison-1.22 / bison.info-2 < prev    next >
Encoding:
Text File  |  1992-09-08  |  49.7 KB  |  1,400 lines  |  [TEXT/EMAC]

  1. Info file bison.info, produced by Makeinfo, -*- Text -*- from input
  2. file bison.texinfo.
  3.  
  4.    This file documents the Bison parser generator.
  5.  
  6.    Copyright (C) 1988, 1989, 1990 Free Software Foundation, Inc.
  7.  
  8.    Permission is granted to make and distribute verbatim copies of
  9. this manual provided the copyright notice and this permission notice
  10. are preserved on all copies.
  11.  
  12.    Permission is granted to copy and distribute modified versions of
  13. this manual under the conditions for verbatim copying, provided also
  14. that the sections entitled "GNU General Public License" and
  15. "Conditions for Using Bison" are included exactly as in the original,
  16. and provided that the entire resulting derived work is distributed
  17. under the terms of a permission notice identical to this one.
  18.  
  19.    Permission is granted to copy and distribute translations of this
  20. manual into another language, under the above conditions for modified
  21. versions, except that the sections entitled "GNU General Public
  22. License", "Conditions for Using Bison" and this permission notice may
  23. be included in translations approved by the Free Software Foundation
  24. instead of in the original English.
  25.  
  26. 
  27. File: bison.info,  Node: Rpcalc Lexer,  Next: Rpcalc Main,  Prev: Rpcalc Expr,  Up: RPN Calc
  28.  
  29. The `rpcalc' Lexical Analyzer
  30. -----------------------------
  31.  
  32.    The lexical analyzer's job is low-level parsing: converting
  33. characters or sequences of characters into tokens.  The Bison parser
  34. gets its tokens by calling the lexical analyzer.  *Note Lexical::.
  35.  
  36.    Only a simple lexical analyzer is needed for the RPN calculator. 
  37. This lexical analyzer skips blanks and tabs, then reads in numbers as
  38. `double' and returns them as `NUM' tokens.  Any other character that
  39. isn't part of a number is a separate token.  Note that the token-code
  40. for such a single-character token is the character itself.
  41.  
  42.    The return value of the lexical analyzer function is a numeric code
  43. which represents a token type.  The same text used in Bison rules to
  44. stand for this token type is also a C expression for the numeric code
  45. for the type.  This works in two ways.  If the token type is a
  46. character literal, then its numeric code is the ASCII code for that
  47. character; you can use the same character literal in the lexical
  48. analyzer to express the number.  If the token type is an identifier,
  49. that identifier is defined by Bison as a C macro whose definition is
  50. the appropriate number.  In this example, therefore, `NUM' becomes a
  51. macro for `yylex' to use.
  52.  
  53.    The semantic value of the token (if it has one) is stored into the
  54. global variable `yylval', which is where the Bison parser will look
  55. for it.  (The C data type of `yylval' is `YYSTYPE', which was defined
  56. at the beginning of the grammar; *note Rpcalc Decls::..)
  57.  
  58.    A token type code of zero is returned if the end-of-file is
  59. encountered.  (Bison recognizes any nonpositive value as indicating
  60. the end of the input.)
  61.  
  62.    Here is the code for the lexical analyzer:
  63.  
  64.      /* Lexical analyzer returns a double floating point
  65.         number on the stack and the token NUM, or the ASCII
  66.         character read if not a number.  Skips all blanks
  67.         and tabs, returns 0 for EOF. */
  68.      
  69.      #include <ctype.h>
  70.      
  71.      yylex ()
  72.      {
  73.        int c;
  74.      
  75.        /* skip white space  */
  76.        while ((c = getchar ()) == ' ' || c == '\t')
  77.          ;
  78.        /* process numbers   */
  79.        if (c == '.' || isdigit (c))
  80.          {
  81.            ungetc (c, stdin);
  82.            scanf ("%lf", &yylval);
  83.            return NUM;
  84.          }
  85.        /* return end-of-file  */
  86.        if (c == EOF)
  87.          return 0;
  88.        /* return single chars */
  89.        return c;
  90.      }
  91.  
  92. 
  93. File: bison.info,  Node: Rpcalc Main,  Next: Rpcalc Error,  Prev: Rpcalc Lexer,  Up: RPN Calc
  94.  
  95. The Controlling Function
  96. ------------------------
  97.  
  98.    In keeping with the spirit of this example, the controlling
  99. function is kept to the bare minimum.  The only requirement is that it
  100. call `yyparse' to start the process of parsing.
  101.  
  102.      main ()
  103.      {
  104.        yyparse ();
  105.      }
  106.  
  107. 
  108. File: bison.info,  Node: Rpcalc Error,  Next: Rpcalc Gen,  Prev: Rpcalc Main,  Up: RPN Calc
  109.  
  110. The Error Reporting Routine
  111. ---------------------------
  112.  
  113.    When `yyparse' detects a syntax error, it calls the error reporting
  114. function `yyerror' to print an error message (usually but not always
  115. `"parse error"').  It is up to the programmer to supply `yyerror'
  116. (*note Interface::.), so here is the definition we will use:
  117.  
  118.      #include <stdio.h>
  119.      
  120.      yyerror (s)  /* Called by yyparse on error */
  121.           char *s;
  122.      {
  123.        printf ("%s\n", s);
  124.      }
  125.  
  126.    After `yyerror' returns, the Bison parser may recover from the error
  127. and continue parsing if the grammar contains a suitable error rule
  128. (*note Error Recovery::.).  Otherwise, `yyparse' returns nonzero.  We
  129. have not written any error rules in this example, so any invalid input
  130. will cause the calculator program to exit.  This is not clean behavior
  131. for a real calculator, but it is adequate in the first example.
  132.  
  133. 
  134. File: bison.info,  Node: Rpcalc Gen,  Next: Rpcalc Compile,  Prev: Rpcalc Error,  Up: RPN Calc
  135.  
  136. Running Bison to Make the Parser
  137. --------------------------------
  138.  
  139.    Before running Bison to produce a parser, we need to decide how to
  140. arrange all the source code in one or more source files.  For such a
  141. simple example, the easiest thing is to put everything in one file. 
  142. The definitions of `yylex', `yyerror' and `main' go at the end, in the
  143. "additional C code" section of the file (*note Grammar Layout::.).
  144.  
  145.    For a large project, you would probably have several source files,
  146. and use `make' to arrange to recompile them.
  147.  
  148.    With all the source in a single file, you use the following command
  149. to convert it into a parser file:
  150.  
  151.      bison FILE_NAME.y
  152.  
  153. In this example the file was called `rpcalc.y' (for "Reverse Polish
  154. CALCulator").  Bison produces a file named `FILE_NAME.tab.c', removing
  155. the `.y' from the original file name. The file output by Bison
  156. contains the source code for `yyparse'.  The additional functions in
  157. the input file (`yylex', `yyerror' and `main') are copied verbatim to
  158. the output.
  159.  
  160. 
  161. File: bison.info,  Node: Rpcalc Compile,  Prev: Rpcalc Gen,  Up: RPN Calc
  162.  
  163. Compiling the Parser File
  164. -------------------------
  165.  
  166.    Here is how to compile and run the parser file:
  167.  
  168.      # List files in current directory.
  169.      % ls
  170.      rpcalc.tab.c  rpcalc.y
  171.  
  172.      
  173.      # Compile the Bison parser.
  174.      # `-lm' tells compiler to search math library for `pow'.
  175.      % cc rpcalc.tab.c -lm -o rpcalc
  176.  
  177.      
  178.      # List files again.
  179.      % ls
  180.      rpcalc  rpcalc.tab.c  rpcalc.y
  181.  
  182.    The file `rpcalc' now contains the executable code.  Here is an
  183. example session using `rpcalc'.
  184.  
  185.      % rpcalc
  186.      4 9 +
  187.      13
  188.      3 7 + 3 4 5 *+-
  189.      -13
  190.      3 7 + 3 4 5 * + - n              Note the unary minus, `n'
  191.      13
  192.      5 6 / 4 n +
  193.      -3.166666667
  194.      3 4 ^                            Exponentiation
  195.      81
  196.      ^D                               End-of-file indicator
  197.      %
  198.  
  199. 
  200. File: bison.info,  Node: Infix Calc,  Next: Simple Error Recovery,  Prev: RPN Calc,  Up: Examples
  201.  
  202. Infix Notation Calculator: `calc'
  203. =================================
  204.  
  205.    We now modify rpcalc to handle infix operators instead of postfix. 
  206. Infix notation involves the concept of operator precedence and the
  207. need for parentheses nested to arbitrary depth.  Here is the Bison
  208. code for `calc.y', an infix desk-top calculator.
  209.  
  210.      /* Infix notation calculator--calc */
  211.      
  212.      %{
  213.      #define YYSTYPE double
  214.      #include <math.h>
  215.      %}
  216.      
  217.      /* BISON Declarations */
  218.      %token NUM
  219.      %left '-' '+'
  220.      %left '*' '/'
  221.      %left NEG     /* negation--unary minus */
  222.      %right '^'    /* exponentiation        */
  223.      
  224.      /* Grammar follows */
  225.      %%
  226.      input:    /* empty string */
  227.              | input line
  228.      ;
  229.      
  230.      line:     '\n'
  231.              | exp '\n'  { printf ("\t%.10g\n", $1); }
  232.      ;
  233.      
  234.      exp:      NUM                { $$ = $1;         }
  235.              | exp '+' exp        { $$ = $1 + $3;    }
  236.              | exp '-' exp        { $$ = $1 - $3;    }
  237.              | exp '*' exp        { $$ = $1 * $3;    }
  238.              | exp '/' exp        { $$ = $1 / $3;    }
  239.              | '-' exp  %prec NEG { $$ = -$2;        }
  240.              | exp '^' exp        { $$ = pow ($1, $3); }
  241.              | '(' exp ')'        { $$ = $2;         }
  242.      ;
  243.      %%
  244.  
  245. The functions `yylex', `yyerror' and `main' can be the same as before.
  246.  
  247.    There are two important new features shown in this code.
  248.  
  249.    In the second section (Bison declarations), `%left' declares token
  250. types and says they are left-associative operators.  The declarations
  251. `%left' and `%right' (right associativity) take the place of `%token'
  252. which is used to declare a token type name without associativity. 
  253. (These tokens are single-character literals, which ordinarily don't
  254. need to be declared.  We declare them here to specify the
  255. associativity.)
  256.  
  257.    Operator precedence is determined by the line ordering of the
  258. declarations; the higher the line number of the declaration (lower on
  259. the page or screen), the higher the precedence.  Hence, exponentiation
  260. has the highest precedence, unary minus (`NEG') is next, followed by
  261. `*' and `/', and so on.  *Note Precedence::.
  262.  
  263.    The other important new feature is the `%prec' in the grammar
  264. section for the unary minus operator.  The `%prec' simply instructs
  265. Bison that the rule `| '-' exp' has the same precedence as `NEG'--in
  266. this case the next-to-highest.  *Note Contextual Precedence::.
  267.  
  268.    Here is a sample run of `calc.y':
  269.  
  270.      % calc
  271.      4 + 4.5 - (34/(8*3+-3))
  272.      6.880952381
  273.      -56 + 2
  274.      -54
  275.      3 ^ 2
  276.      9
  277.  
  278. 
  279. File: bison.info,  Node: Simple Error Recovery,  Next: Multi-function Calc,  Prev: Infix Calc,  Up: Examples
  280.  
  281. Simple Error Recovery
  282. =====================
  283.  
  284.    Up to this point, this manual has not addressed the issue of "error
  285. recovery"--how to continue parsing after the parser detects a syntax
  286. error.  All we have handled is error reporting with `yyerror'.  Recall
  287. that by default `yyparse' returns after calling `yyerror'.  This means
  288. that an erroneous input line causes the calculator program to exit. 
  289. Now we show how to rectify this deficiency.
  290.  
  291.    The Bison language itself includes the reserved word `error', which
  292. may be included in the grammar rules.  In the example below it has
  293. been added to one of the alternatives for `line':
  294.  
  295.      line:     '\n'
  296.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  297.              | error '\n' { yyerrok;                  }
  298.      ;
  299.  
  300.    This addition to the grammar allows for simple error recovery in
  301. the event of a parse error.  If an expression that cannot be evaluated
  302. is read, the error will be recognized by the third rule for `line',
  303. and parsing will continue.  (The `yyerror' function is still called
  304. upon to print its message as well.)  The action executes the statement
  305. `yyerrok', a macro defined automatically by Bison; its meaning is that
  306. error recovery is complete (*note Error Recovery::.).  Note the
  307. difference between `yyerrok' and `yyerror'; neither one is a misprint.
  308.  
  309.    This form of error recovery deals with syntax errors.  There are
  310. other kinds of errors; for example, division by zero, which raises an
  311. exception signal that is normally fatal.  A real calculator program
  312. must handle this signal and use `longjmp' to return to `main' and
  313. resume parsing input lines; it would also have to discard the rest of
  314. the current line of input.  We won't discuss this issue further
  315. because it is not specific to Bison programs.
  316.  
  317. 
  318. File: bison.info,  Node: Multi-function Calc,  Next: Exercises,  Prev: Simple Error Recovery,  Up: Examples
  319.  
  320. Multi-Function Calculator: `mfcalc'
  321. ===================================
  322.  
  323.    Now that the basics of Bison have been discussed, it is time to
  324. move on to a more advanced problem.  The above calculators provided
  325. only five functions, `+', `-', `*', `/' and `^'.  It would be nice to
  326. have a calculator that provides other mathematical functions such as
  327. `sin', `cos', etc.
  328.  
  329.    It is easy to add new operators to the infix calculator as long as
  330. they are only single-character literals.  The lexical analyzer `yylex'
  331. passes back all non-number characters as tokens, so new grammar rules
  332. suffice for adding a new operator.  But we want something more
  333. flexible: built-in functions whose syntax has this form:
  334.  
  335.      FUNCTION_NAME (ARGUMENT)
  336.  
  337. At the same time, we will add memory to the calculator, by allowing you
  338. to create named variables, store values in them, and use them later. 
  339. Here is a sample session with the multi-function calculator:
  340.  
  341.      % acalc
  342.      pi = 3.141592653589
  343.      3.1415926536
  344.      sin(pi)
  345.      0.0000000000
  346.      alpha = beta1 = 2.3
  347.      2.3000000000
  348.      alpha
  349.      2.3000000000
  350.      ln(alpha)
  351.      0.8329091229
  352.      exp(ln(beta1))
  353.      2.3000000000
  354.      %
  355.  
  356.    Note that multiple assignment and nested function calls are
  357. permitted.
  358.  
  359. * Menu:
  360.  
  361. * Decl: Mfcalc Decl.     Bison declarations for multi-function calculator.
  362. * Rules: Mfcalc Rules.   Grammar rules for the calculator.
  363. * Symtab: Mfcalc Symtab. Symbol table management subroutines.
  364.  
  365. 
  366. File: bison.info,  Node: Mfcalc Decl,  Next: Mfcalc Rules,  Prev: Multi-function Calc,  Up: Multi-function Calc
  367.  
  368. Declarations for `mfcalc'
  369. -------------------------
  370.  
  371.    Here are the C and Bison declarations for the multi-function
  372. calculator.
  373.  
  374.      %{
  375.      #include <math.h>  /* For math functions, cos(), sin(), etc. */
  376.      #include "calc.h"  /* Contains definition of `symrec'        */
  377.      %}
  378.      %union {
  379.      double     val;  /* For returning numbers.                   */
  380.      symrec  *tptr;   /* For returning symbol-table pointers      */
  381.      }
  382.      
  383.      %token <val>  NUM        /* Simple double precision number   */
  384.      %token <tptr> VAR FNCT   /* Variable and Function            */
  385.      %type  <val>  exp
  386.      
  387.      %right '='
  388.      %left '-' '+'
  389.      %left '*' '/'
  390.      %left NEG     /* Negation--unary minus */
  391.      %right '^'    /* Exponentiation        */
  392.      
  393.      /* Grammar follows */
  394.      
  395.      %%
  396.  
  397.    The above grammar introduces only two new features of the Bison
  398. language.  These features allow semantic values to have various data
  399. types (*note Multiple Types::.).
  400.  
  401.    The `%union' declaration specifies the entire list of possible
  402. types; this is instead of defining `YYSTYPE'.  The allowable types are
  403. now double-floats (for `exp' and `NUM') and pointers to entries in the
  404. symbol table.  *Note Union Decl::.
  405.  
  406.    Since values can now have various types, it is necessary to
  407. associate a type with each grammar symbol whose semantic value is
  408. used.  These symbols are `NUM', `VAR', `FNCT', and `exp'.  Their
  409. declarations are augmented with information about their data type
  410. (placed between angle brackets).
  411.  
  412.    The Bison construct `%type' is used for declaring nonterminal
  413. symbols, just as `%token' is used for declaring token types.  We have
  414. not used `%type' before because nonterminal symbols are normally
  415. declared implicitly by the rules that define them.  But `exp' must be
  416. declared explicitly so we can specify its value type.  *Note Type
  417. Decl::.
  418.  
  419. 
  420. File: bison.info,  Node: Mfcalc Rules,  Next: Mfcalc Symtab,  Prev: Mfcalc Decl,  Up: Multi-function Calc
  421.  
  422. Grammar Rules for `mfcalc'
  423. --------------------------
  424.  
  425.    Here are the grammar rules for the multi-function calculator.  Most
  426. of them are copied directly from `calc'; three rules, those which
  427. mention `VAR' or `FNCT', are new.
  428.  
  429.      input:   /* empty */
  430.              | input line
  431.      ;
  432.      
  433.      line:
  434.                '\n'
  435.              | exp '\n'   { printf ("\t%.10g\n", $1); }
  436.              | error '\n' { yyerrok;                  }
  437.      ;
  438.      
  439.      exp:      NUM                { $$ = $1;                         }
  440.              | VAR                { $$ = $1->value.var;              }
  441.              | VAR '=' exp        { $$ = $3; $1->value.var = $3;     }
  442.              | FNCT '(' exp ')'   { $$ = (*($1->value.fnctptr))($3); }
  443.              | exp '+' exp        { $$ = $1 + $3;                    }
  444.              | exp '-' exp        { $$ = $1 - $3;                    }
  445.              | exp '*' exp        { $$ = $1 * $3;                    }
  446.              | exp '/' exp        { $$ = $1 / $3;                    }
  447.              | '-' exp  %prec NEG { $$ = -$2;                        }
  448.              | exp '^' exp        { $$ = pow ($1, $3);               }
  449.              | '(' exp ')'        { $$ = $2;                         }
  450.      ;
  451.      /* End of grammar */
  452.      %%
  453.  
  454. 
  455. File: bison.info,  Node: Mfcalc Symtab,  Prev: Mfcalc Rules,  Up: Multi-function Calc
  456.  
  457. The `mfcalc' Symbol Table
  458. -------------------------
  459.  
  460.    The multi-function calculator requires a symbol table to keep track
  461. of the names and meanings of variables and functions.  This doesn't
  462. affect the grammar rules (except for the actions) or the Bison
  463. declarations, but it requires some additional C functions for support.
  464.  
  465.    The symbol table itself consists of a linked list of records.  Its
  466. definition, which is kept in the header `calc.h', is as follows.  It
  467. provides for either functions or variables to be placed in the table.
  468.  
  469.      /* Data type for links in the chain of symbols.      */
  470.      struct symrec
  471.      {
  472.        char *name;  /* name of symbol                     */
  473.        int type;    /* type of symbol: either VAR or FNCT */
  474.        union {
  475.          double var;           /* value of a VAR          */
  476.          double (*fnctptr)();  /* value of a FNCT         */
  477.        } value;
  478.        struct symrec *next;    /* link field              */
  479.      };
  480.      
  481.      typedef struct symrec symrec;
  482.      
  483.      /* The symbol table: a chain of `struct symrec'.     */
  484.      extern symrec *sym_table;
  485.      
  486.      symrec *putsym ();
  487.      symrec *getsym ();
  488.  
  489.    The new version of `main' includes a call to `init_table', a
  490. function that initializes the symbol table.  Here it is, and
  491. `init_table' as well:
  492.  
  493.      #include <stdio.h>
  494.      
  495.      main ()
  496.      {
  497.        init_table ();
  498.        yyparse ();
  499.      }
  500.      
  501.      yyerror (s)  /* Called by yyparse on error */
  502.           char *s;
  503.      {
  504.        printf ("%s\n", s);
  505.      }
  506.      
  507.      struct init
  508.      {
  509.        char *fname;
  510.        double (*fnct)();
  511.      };
  512.      
  513.      struct init arith_fncts[]
  514.        = {
  515.            "sin", sin,
  516.            "cos", cos,
  517.            "atan", atan,
  518.            "ln", log,
  519.            "exp", exp,
  520.            "sqrt", sqrt,
  521.            0, 0
  522.          };
  523.      
  524.      /* The symbol table: a chain of `struct symrec'.  */
  525.      symrec *sym_table = (symrec *)0;
  526.      
  527.      init_table ()  /* puts arithmetic functions in table. */
  528.      {
  529.        int i;
  530.        symrec *ptr;
  531.        for (i = 0; arith_fncts[i].fname != 0; i++)
  532.          {
  533.            ptr = putsym (arith_fncts[i].fname, FNCT);
  534.            ptr->value.fnctptr = arith_fncts[i].fnct;
  535.          }
  536.      }
  537.  
  538.    By simply editing the initialization list and adding the necessary
  539. include files, you can add additional functions to the calculator.
  540.  
  541.    Two important functions allow look-up and installation of symbols
  542. in the symbol table.  The function `putsym' is passed a name and the
  543. type (`VAR' or `FNCT') of the object to be installed.  The object is
  544. linked to the front of the list, and a pointer to the object is
  545. returned.  The function `getsym' is passed the name of the symbol to
  546. look up.  If found, a pointer to that symbol is returned; otherwise
  547. zero is returned.
  548.  
  549.      symrec *
  550.      putsym (sym_name,sym_type)
  551.           char *sym_name;
  552.           int sym_type;
  553.      {
  554.        symrec *ptr;
  555.        ptr = (symrec *) malloc (sizeof (symrec));
  556.        ptr->name = (char *) malloc (strlen (sym_name) + 1);
  557.        strcpy (ptr->name,sym_name);
  558.        ptr->type = sym_type;
  559.        ptr->value.var = 0; /* set value to 0 even if fctn.  */
  560.        ptr->next = (struct symrec *)sym_table;
  561.        sym_table = ptr;
  562.        return ptr;
  563.      }
  564.      
  565.      symrec *
  566.      getsym (sym_name)
  567.           char *sym_name;
  568.      {
  569.        symrec *ptr;
  570.        for (ptr = sym_table; ptr != (symrec *) 0;
  571.             ptr = (symrec *)ptr->next)
  572.          if (strcmp (ptr->name,sym_name) == 0)
  573.            return ptr;
  574.        return 0;
  575.      }
  576.  
  577.    The function `yylex' must now recognize variables, numeric values,
  578. and the single-character arithmetic operators.  Strings of alphanumeric
  579. characters with a leading nondigit are recognized as either variables
  580. or functions depending on what the symbol table says about them.
  581.  
  582.    The string is passed to `getsym' for look up in the symbol table. 
  583. If the name appears in the table, a pointer to its location and its
  584. type (`VAR' or `FNCT') is returned to `yyparse'.  If it is not already
  585. in the table, then it is installed as a `VAR' using `putsym'.  Again,
  586. a pointer and its type (which must be `VAR') is returned to `yyparse'.
  587.  
  588.    No change is needed in the handling of numeric values and arithmetic
  589. operators in `yylex'.
  590.  
  591.      #include <ctype.h>
  592.      yylex ()
  593.      {
  594.        int c;
  595.      
  596.        /* Ignore whitespace, get first nonwhite character.  */
  597.        while ((c = getchar ()) == ' ' || c == '\t');
  598.      
  599.        if (c == EOF)
  600.          return 0;
  601.      
  602.        /* Char starts a number => parse the number.         */
  603.        if (c == '.' || isdigit (c))
  604.          {
  605.            ungetc (c, stdin);
  606.            scanf ("%lf", &yylval.val);
  607.            return NUM;
  608.          }
  609.      
  610.        /* Char starts an identifier => read the name.       */
  611.        if (isalpha (c))
  612.          {
  613.            symrec *s;
  614.            static char *symbuf = 0;
  615.            static int length = 0;
  616.            int i;
  617.      
  618.            /* Initially make the buffer long enough
  619.               for a 40-character symbol name.  */
  620.            if (length == 0)
  621.              length = 40, symbuf = (char *)malloc (length + 1);
  622.      
  623.            i = 0;
  624.            do
  625.              {
  626.                /* If buffer is full, make it bigger.        */
  627.                if (i == length)
  628.                  {
  629.                    length *= 2;
  630.                    symbuf = (char *)realloc (symbuf, length + 1);
  631.                  }
  632.                /* Add this character to the buffer.         */
  633.                symbuf[i++] = c;
  634.                /* Get another character.                    */
  635.                c = getchar ();
  636.              }
  637.            while (c != EOF && isalnum (c));
  638.      
  639.            ungetc (c, stdin);
  640.            symbuf[i] = '\0';
  641.      
  642.            s = getsym (symbuf);
  643.            if (s == 0)
  644.              s = putsym (symbuf, VAR);
  645.            yylval.tptr = s;
  646.            return s->type;
  647.          }
  648.      
  649.        /* Any other character is a token by itself.        */
  650.        return c;
  651.      }
  652.  
  653.    This program is both powerful and flexible. You may easily add new
  654. functions, and it is a simple job to modify this code to install
  655. predefined variables such as `pi' or `e' as well.
  656.  
  657. 
  658. File: bison.info,  Node: Exercises,  Prev: Multi-function calc,  Up: Examples
  659.  
  660. Exercises
  661. =========
  662.  
  663.   1. Add some new functions from `math.h' to the initialization list.
  664.  
  665.   2. Add another array that contains constants and their values.  Then
  666.      modify `init_table' to add these constants to the symbol table. 
  667.      It will be easiest to give the constants type `VAR'.
  668.  
  669.   3. Make the program report an error if the user refers to an
  670.      uninitialized variable in any way except to store a value in it.
  671.  
  672. 
  673. File: bison.info,  Node: Grammar File,  Next: Interface,  Prev: Examples,  Up: Top
  674.  
  675. Bison Grammar Files
  676. *******************
  677.  
  678.    Bison takes as input a context-free grammar specification and
  679. produces a C-language function that recognizes correct instances of
  680. the grammar.
  681.  
  682.    The Bison grammar input file conventionally has a name ending in
  683. `.y'.
  684.  
  685. * Menu:
  686.  
  687. * Grammar Outline::    Overall layout of the grammar file.
  688. * Symbols::            Terminal and nonterminal symbols.
  689. * Rules::              How to write grammar rules.
  690. * Recursion::          Writing recursive rules.
  691. * Semantics::          Semantic values and actions.
  692. * Declarations::       All kinds of Bison declarations are described here.
  693. * Multiple Parsers::   Putting more than one Bison parser in one program.
  694.  
  695. 
  696. File: bison.info,  Node: Grammar Outline,  Next: Symbols,  Prev: Grammar File,  Up: Grammar File
  697.  
  698. Outline of a Bison Grammar
  699. ==========================
  700.  
  701.    A Bison grammar file has four main sections, shown here with the
  702. appropriate delimiters:
  703.  
  704.      %{
  705.      C DECLARATIONS
  706.      %}
  707.      
  708.      BISON DECLARATIONS
  709.      
  710.      %%
  711.      GRAMMAR RULES
  712.      %%
  713.      
  714.      ADDITIONAL C CODE
  715.  
  716.    Comments enclosed in `/* ... */' may appear in any of the sections.
  717.  
  718. * Menu:
  719.  
  720. * C Declarations::      Syntax and usage of the C declarations section.
  721. * Bison Declarations::  Syntax and usage of the Bison declarations section.
  722. * Grammar Rules::       Syntax and usage of the grammar rules section.
  723. * C Code::              Syntax and usage of the additional C code section.
  724.  
  725. 
  726. File: bison.info,  Node: C Declarations,  Next: Bison Declarations,  Prev: Grammar Outline,  Up: Grammar Outline
  727.  
  728. The C Declarations Section
  729. --------------------------
  730.  
  731.    The C DECLARATIONS section contains macro definitions and
  732. declarations of functions and variables that are used in the actions
  733. in the grammar rules.  These are copied to the beginning of the parser
  734. file so that they precede the definition of `yyparse'.  You can use
  735. `#include' to get the declarations from a header file.  If you don't
  736. need any C declarations, you may omit the `%{' and `%}' delimiters
  737. that bracket this section.
  738.  
  739. 
  740. File: bison.info,  Node: Bison Declarations,  Next: Grammar Rules,  Prev: C Declarations,  Up: Grammar Outline
  741.  
  742. The Bison Declarations Section
  743. ------------------------------
  744.  
  745.    The BISON DECLARATIONS section contains declarations that define
  746. terminal and nonterminal symbols, specify precedence, and so on.  In
  747. some simple grammars you may not need any declarations.  *Note
  748. Declarations::.
  749.  
  750. 
  751. File: bison.info,  Node: Grammar Rules,  Next: C Code,  Prev: Bison Declarations,  Up: Grammar Outline
  752.  
  753. The Grammar Rules Section
  754. -------------------------
  755.  
  756.    The "grammar rules" section contains one or more Bison grammar
  757. rules, and nothing else.  *Note Rules::.
  758.  
  759.    There must always be at least one grammar rule, and the first `%%'
  760. (which precedes the grammar rules) may never be omitted even if it is
  761. the first thing in the file.
  762.  
  763. 
  764. File: bison.info,  Node: C Code,  Prev: Grammar Rules,  Up: Grammar Outline
  765.  
  766. The Additional C Code Section
  767. -----------------------------
  768.  
  769.    The ADDITIONAL C CODE section is copied verbatim to the end of the
  770. parser file, just as the C DECLARATIONS section is copied to the
  771. beginning.  This is the most convenient place to put anything that you
  772. want to have in the parser file but which need not come before the
  773. definition of `yyparse'.  For example, the definitions of `yylex' and
  774. `yyerror' often go here.  *Note Interface::.
  775.  
  776.    If the last section is empty, you may omit the `%%' that separates
  777. it from the grammar rules.
  778.  
  779.    The Bison parser itself contains many static variables whose names
  780. start with `yy' and many macros whose names start with `YY'.  It is a
  781. good idea to avoid using any such names (except those documented in
  782. this manual) in the additional C code section of the grammar file.
  783.  
  784. 
  785. File: bison.info,  Node: Symbols,  Next: Rules,  Prev: Grammar Outline,  Up: Grammar File
  786.  
  787. Symbols, Terminal and Nonterminal
  788. =================================
  789.  
  790.    "Symbols" in Bison grammars represent the grammatical
  791. classifications of the language.
  792.  
  793.    A "terminal symbol" (also known as a "token type") represents a
  794. class of syntactically equivalent tokens.  You use the symbol in
  795. grammar rules to mean that a token in that class is allowed.  The
  796. symbol is represented in the Bison parser by a numeric code, and the
  797. `yylex' function returns a token type code to indicate what kind of
  798. token has been read.  You don't need to know what the code value is;
  799. you can use the symbol to stand for it.
  800.  
  801.    A "nonterminal symbol" stands for a class of syntactically
  802. equivalent groupings.  The symbol name is used in writing grammar
  803. rules.  By convention, it should be all lower case.
  804.  
  805.    Symbol names can contain letters, digits (not at the beginning),
  806. underscores and periods.  Periods make sense only in nonterminals.
  807.  
  808.    There are two ways of writing terminal symbols in the grammar:
  809.  
  810.    * A "named token type" is written with an identifier, like an
  811.      identifier in C.  By convention, it should be all upper case. 
  812.      Each such name must be defined with a Bison declaration such as
  813.      `%token'.  *Note Token Decl::.
  814.  
  815.    * A "character token type" (or "literal token") is written in the
  816.      grammar using the same syntax used in C for character constants;
  817.      for example, `'+'' is a character token type.  A character token
  818.      type doesn't need to be declared unless you need to specify its
  819.      semantic value data type (*note Value Type::.), associativity, or
  820.      precedence (*note Precedence::.).
  821.  
  822.      By convention, a character token type is used only to represent a
  823.      token that consists of that particular character.  Thus, the token
  824.      type `'+'' is used to represent the character `+' as a token. 
  825.      Nothing enforces this convention, but if you depart from it, your
  826.      program will confuse other readers.
  827.  
  828.      All the usual escape sequences used in character literals in C
  829.      can be used in Bison as well, but you must not use the null
  830.      character as a character literal because its ASCII code, zero, is
  831.      the code `yylex' returns for end-of-input (*note Calling
  832.      Convention::.).
  833.  
  834.    How you choose to write a terminal symbol has no effect on its
  835. grammatical meaning.  That depends only on where it appears in rules
  836. and on when the parser function returns that symbol.
  837.  
  838.    The value returned by `yylex' is always one of the terminal symbols
  839. (or 0 for end-of-input).  Whichever way you write the token type in the
  840. grammar rules, you write it the same way in the definition of `yylex'. 
  841. The numeric code for a character token type is simply the ASCII code
  842. for the character, so `yylex' can use the identical character constant
  843. to generate the requisite code.  Each named token type becomes a C
  844. macro in the parser file, so `yylex' can use the name to stand for the
  845. code.  (This is why periods don't make sense in terminal symbols.) 
  846. *Note Calling Convention::.
  847.  
  848.    If `yylex' is defined in a separate file, you need to arrange for
  849. the token-type macro definitions to be available there.  Use the `-d'
  850. option when you run Bison, so that it will write these macro
  851. definitions into a separate header file `NAME.tab.h' which you can
  852. include in the other source files that need it.  *Note Invocation::.
  853.  
  854.    The symbol `error' is a terminal symbol reserved for error recovery
  855. (*note Error Recovery::.); you shouldn't use it for any other purpose. 
  856. In particular, `yylex' should never return this value.
  857.  
  858. 
  859. File: bison.info,  Node: Rules,  Next: Recursion,  Prev: Symbols,  Up: Grammar File
  860.  
  861. Syntax of Grammar Rules
  862. =======================
  863.  
  864.    A Bison grammar rule has the following general form:
  865.  
  866.      RESULT: COMPONENTS...
  867.              ;
  868.  
  869. where RESULT is the nonterminal symbol that this rule describes and
  870. COMPONENTS are various terminal and nonterminal symbols that are put
  871. together by this rule (*note Symbols::.).
  872.  
  873.    For example,
  874.  
  875.      exp:      exp '+' exp
  876.              ;
  877.  
  878. says that two groupings of type `exp', with a `+' token in between,
  879. can be combined into a larger grouping of type `exp'.
  880.  
  881.    Whitespace in rules is significant only to separate symbols.  You
  882. can add extra whitespace as you wish.
  883.  
  884.    Scattered among the components can be ACTIONS that determine the
  885. semantics of the rule.  An action looks like this:
  886.  
  887.      {C STATEMENTS}
  888.  
  889. Usually there is only one action and it follows the components.  *Note
  890. Actions::.
  891.  
  892.    Multiple rules for the same RESULT can be written separately or can
  893. be joined with the vertical-bar character `|' as follows:
  894.  
  895.      RESULT:   RULE1-COMPONENTS...
  896.              | RULE2-COMPONENTS...
  897.              ...
  898.              ;
  899.  
  900. They are still considered distinct rules even when joined in this way.
  901.  
  902.    If COMPONENTS in a rule is empty, it means that RESULT can match
  903. the empty string.  For example, here is how to define a
  904. comma-separated sequence of zero or more `exp' groupings:
  905.  
  906.      expseq:   /* empty */
  907.              | expseq1
  908.              ;
  909.  
  910.      
  911.      expseq1:  exp
  912.              | expseq1 ',' exp
  913.              ;
  914.  
  915. It is customary to write a comment `/* empty */' in each rule with no
  916. components.
  917.  
  918. 
  919. File: bison.info,  Node: Recursion,  Next: Semantics,  Prev: Rules,  Up: Grammar File
  920.  
  921. Recursive Rules
  922. ===============
  923.  
  924.    A rule is called "recursive" when its RESULT nonterminal appears
  925. also on its right hand side.  Nearly all Bison grammars need to use
  926. recursion, because that is the only way to define a sequence of any
  927. number of somethings.  Consider this recursive definition of a
  928. comma-separated sequence of one or more expressions:
  929.  
  930.      expseq1:  exp
  931.              | expseq1 ',' exp
  932.              ;
  933.  
  934. Since the recursive use of `expseq1' is the leftmost symbol in the
  935. right hand side, we call this "left recursion".  By contrast, here the
  936. same construct is defined using "right recursion":
  937.  
  938.      expseq1:  exp
  939.              | exp ',' expseq1
  940.              ;
  941.  
  942. Any kind of sequence can be defined using either left recursion or
  943. right recursion, but you should always use left recursion, because it
  944. can parse a sequence of any number of elements with bounded stack
  945. space.  Right recursion uses up space on the Bison stack in proportion
  946. to the number of elements in the sequence, because all the elements
  947. must be shifted onto the stack before the rule can be applied even
  948. once.  *Note The Algorithm of the Bison Parser: Algorithm, for further
  949. explanation of this.
  950.  
  951.    "Indirect" or "mutual" recursion occurs when the result of the rule
  952. does not appear directly on its right hand side, but does appear in
  953. rules for other nonterminals which do appear on its right hand side.
  954.  
  955.    For example:
  956.  
  957.      expr:     primary
  958.              | primary '+' primary
  959.              ;
  960.  
  961.      
  962.      primary:  constant
  963.              | '(' expr ')'
  964.              ;
  965.  
  966. defines two mutually-recursive nonterminals, since each refers to the
  967. other.
  968.  
  969. 
  970. File: bison.info,  Node: Semantics,  Next: Declarations,  Prev: Recursion,  Up: Grammar File
  971.  
  972. Defining Language Semantics
  973. ===========================
  974.  
  975.    The grammar rules for a language determine only the syntax.  The
  976. semantics are determined by the semantic values associated with
  977. various tokens and groupings, and by the actions taken when various
  978. groupings are recognized.
  979.  
  980.    For example, the calculator calculates properly because the value
  981. associated with each expression is the proper number; it adds properly
  982. because the action for the grouping `X + Y' is to add the numbers
  983. associated with X and Y.
  984.  
  985. * Menu:
  986.  
  987. * Value Type::       Specifying one data type for all semantic values.
  988. * Multiple Types::   Specifying several alternative data types.
  989. * Actions::          An action is the semantic definition of a grammar rule.
  990. * Action Types::     Specifying data types for actions to operate on.
  991. * Mid-Rule Actions:: Most actions go at the end of a rule.
  992.                       This says when, why and how to use the exceptional
  993.                       action in the middle of a rule.
  994.  
  995. 
  996. File: bison.info,  Node: Value Type,  Next: Multiple Types,  Prev: Semantics,  Up: Semantics
  997.  
  998. Data Types of Semantic Values
  999. -----------------------------
  1000.  
  1001.    In a simple program it may be sufficient to use the same data type
  1002. for the semantic values of all language constructs.  This was true in
  1003. the RPN and infix calculator examples (*note RPN Calc::.).
  1004.  
  1005.    Bison's default is to use type `int' for all semantic values.  To
  1006. specify some other type, define `YYSTYPE' as a macro, like this:
  1007.  
  1008.      #define YYSTYPE double
  1009.  
  1010. This macro definition must go in the C declarations section of the
  1011. grammar file (*note Grammar Outline::.).
  1012.  
  1013. 
  1014. File: bison.info,  Node: Multiple Types,  Next: Actions,  Prev: Value Type,  Up: Semantics
  1015.  
  1016. More Than One Value Type
  1017. ------------------------
  1018.  
  1019.    In most programs, you will need different data types for different
  1020. kinds of tokens and groupings.  For example, a numeric constant may
  1021. need type `int' or `long', while a string constant needs type `char *',
  1022. and an identifier might need a pointer to an entry in the symbol table.
  1023.  
  1024.    To use more than one data type for semantic values in one parser,
  1025. Bison requires you to do two things:
  1026.  
  1027.    * Specify the entire collection of possible data types, with the
  1028.      `%union' Bison declaration (*note Union Decl::.).
  1029.  
  1030.    * Choose one of those types for each symbol (terminal or
  1031.      nonterminal) for which semantic values are used.  This is done
  1032.      for tokens with the `%token' Bison declaration (*note Token
  1033.      Decl::.) and for groupings with the `%type' Bison declaration
  1034.      (*note Type Decl::.).
  1035.  
  1036. 
  1037. File: bison.info,  Node: Actions,  Next: Action Types,  Prev: Multiple Types,  Up: Semantics
  1038.  
  1039. Actions
  1040. -------
  1041.  
  1042.    An action accompanies a syntactic rule and contains C code to be
  1043. executed each time an instance of that rule is recognized.  The task
  1044. of most actions is to compute a semantic value for the grouping built
  1045. by the rule from the semantic values associated with tokens or smaller
  1046. groupings.
  1047.  
  1048.    An action consists of C statements surrounded by braces, much like a
  1049. compound statement in C.  It can be placed at any position in the
  1050. rule; it is executed at that position.  Most rules have just one
  1051. action at the end of the rule, following all the components.  Actions
  1052. in the middle of a rule are tricky and used only for special purposes
  1053. (*note Mid-Rule Actions::.).
  1054.  
  1055.    The C code in an action can refer to the semantic values of the
  1056. components matched by the rule with the construct `$N', which stands
  1057. for the value of the Nth component.  The semantic value for the
  1058. grouping being constructed is `$$'.  (Bison translates both of these
  1059. constructs into array element references when it copies the actions
  1060. into the parser file.)
  1061.  
  1062.    Here is a typical example:
  1063.  
  1064.      exp:    ...
  1065.              | exp '+' exp
  1066.                  { $$ = $1 + $3; }
  1067.  
  1068. This rule constructs an `exp' from two smaller `exp' groupings
  1069. connected by a plus-sign token.  In the action, `$1' and `$3' refer to
  1070. the semantic values of the two component `exp' groupings, which are
  1071. the first and third symbols on the right hand side of the rule.  The
  1072. sum is stored into `$$' so that it becomes the semantic value of the
  1073. addition-expression just recognized by the rule.  If there were a
  1074. useful semantic value associated with the `+' token, it could be
  1075. referred to as `$2'.
  1076.  
  1077.    `$N' with N zero or negative is allowed for reference to tokens and
  1078. groupings on the stack *before* those that match the current rule. 
  1079. This is a very risky practice, and to use it reliably you must be
  1080. certain of the context in which the rule is applied.  Here is a case
  1081. in which you can use this reliably:
  1082.  
  1083.      foo:      expr bar '+' expr  { ... }
  1084.              | expr bar '-' expr  { ... }
  1085.              ;
  1086.  
  1087.      
  1088.      bar:      /* empty */
  1089.              { previous_expr = $0; }
  1090.              ;
  1091.  
  1092.    As long as `bar' is used only in the fashion shown here, `$0'
  1093. always refers to the `expr' which precedes `bar' in the definition of
  1094. `foo'.
  1095.  
  1096. 
  1097. File: bison.info,  Node: Action Types,  Next: Mid-Rule Actions,  Prev: Actions,  Up: Semantics
  1098.  
  1099. Data Types of Values in Actions
  1100. -------------------------------
  1101.  
  1102.    If you have chosen a single data type for semantic values, the `$$'
  1103. and `$N' constructs always have that data type.
  1104.  
  1105.    If you have used `%union' to specify a variety of data types, then
  1106. you must declare a choice among these types for each terminal or
  1107. nonterminal symbol that can have a semantic value.  Then each time you
  1108. use `$$' or `$N', its data type is determined by which symbol it
  1109. refers to in the rule.  In this example,
  1110.  
  1111.      exp:    ...
  1112.              | exp '+' exp
  1113.                  { $$ = $1 + $3; }
  1114.  
  1115. `$1' and `$3' refer to instances of `exp', so they all have the data
  1116. type declared for the nonterminal symbol `exp'.  If `$2' were used, it
  1117. would have the data type declared for the terminal symbol `'+'',
  1118. whatever that might be.
  1119.  
  1120.    Alternatively, you can specify the data type when you refer to the
  1121. value, by inserting `<TYPE>' after the `$' at the beginning of the
  1122. reference.  For example, if you have defined types as shown here:
  1123.  
  1124.      %union {
  1125.        int itype;
  1126.        double dtype;
  1127.      }
  1128.  
  1129. then you can write `$<itype>1' to refer to the first subunit of the
  1130. rule as an integer, or `$<dtype>1' to refer to it as a double.
  1131.  
  1132. 
  1133. File: bison.info,  Node: Mid-Rule Actions,  Prev: Action Types,  Up: Semantics
  1134.  
  1135. Actions in Mid-Rule
  1136. -------------------
  1137.  
  1138.    Occasionally it is useful to put an action in the middle of a rule. 
  1139. These actions are written just like usual end-of-rule actions, but they
  1140. are executed before the parser even recognizes the following
  1141. components.
  1142.  
  1143.    A mid-rule action may refer to the components preceding it using
  1144. `$N', but it may not refer to subsequent components because it is run
  1145. before they are parsed.
  1146.  
  1147.    The mid-rule action itself counts as one of the components of the
  1148. rule.  This makes a difference when there is another action later in
  1149. the same rule (and usually there is another at the end): you have to
  1150. count the actions along with the symbols when working out which number
  1151. N to use in `$N'.
  1152.  
  1153.    The mid-rule action can also have a semantic value.  This can be set
  1154. within that action by an assignment to `$$', and can referred to by
  1155. actions later in the rule using `$N'.  Since there is no symbol to
  1156. name the action, there is no way to declare a data type for the value
  1157. in advance, so you must use the `$<...>' construct to specify a data
  1158. type each time you refer to this value.
  1159.  
  1160.    There is no way to set the value of the entire rule with a mid-rule
  1161. action, because assignments to `$$' do not have that effect.  The only
  1162. way to set the value for the entire rule is with an ordinary action at
  1163. the end of the rule.
  1164.  
  1165.    Here is an example from a hypothetical compiler, handling a `let'
  1166. statement that looks like `let (VARIABLE) STATEMENT' and serves to
  1167. create a variable named VARIABLE temporarily for the duration of
  1168. STATEMENT.  To parse this construct, we must put VARIABLE into the
  1169. symbol table while STATEMENT is parsed, then remove it afterward. 
  1170. Here is how it is done:
  1171.  
  1172.      stmt:   LET '(' var ')'
  1173.                      { $<context>$ = push_context ();
  1174.                        declare_variable ($3); }
  1175.              stmt    { $$ = $6;
  1176.                        pop_context ($<context>5); }
  1177.  
  1178. As soon as `let (VARIABLE)' has been recognized, the first action is
  1179. run.  It saves a copy of the current semantic context (the list of
  1180. accessible variables) as its semantic value, using alternative
  1181. `context' in the data-type union.  Then it calls `declare_variable' to
  1182. add the new variable to that list.  Once the first action is finished,
  1183. the embedded statement `stmt' can be parsed.  Note that the mid-rule
  1184. action is component number 5, so the `stmt' is component number 6.
  1185.  
  1186.    After the embedded statement is parsed, its semantic value becomes
  1187. the value of the entire `let'-statement.  Then the semantic value from
  1188. the earlier action is used to restore the prior list of variables. 
  1189. This removes the temporary `let'-variable from the list so that it
  1190. won't appear to exist while the rest of the program is parsed.
  1191.  
  1192.    Taking action before a rule is completely recognized often leads to
  1193. conflicts since the parser must commit to a parse in order to execute
  1194. the action.  For example, the following two rules, without mid-rule
  1195. actions, can coexist in a working parser because the parser can shift
  1196. the open-brace token and look at what follows before deciding whether
  1197. there is a declaration or not:
  1198.  
  1199.      compound: '{' declarations statements '}'
  1200.              | '{' statements '}'
  1201.              ;
  1202.  
  1203. But when we add a mid-rule action as follows, the rules become
  1204. nonfunctional:
  1205.  
  1206.      compound: { prepare_for_local_variables (); }
  1207.                '{' declarations statements '}'
  1208.  
  1209.           | '{' statements '}'
  1210.              ;
  1211.  
  1212. Now the parser is forced to decide whether to run the mid-rule action
  1213. when it has read no farther than the open-brace.  In other words, it
  1214. must commit to using one rule or the other, without sufficient
  1215. information to do it correctly.  (The open-brace token is what is
  1216. called the "look-ahead" token at this time, since the parser is still
  1217. deciding what to do about it.  *Note Look-Ahead::.)
  1218.  
  1219.    You might think that you could correct the problem by putting
  1220. identical actions into the two rules, like this:
  1221.  
  1222.      compound: { prepare_for_local_variables (); }
  1223.                '{' declarations statements '}'
  1224.              | { prepare_for_local_variables (); }
  1225.                '{' statements '}'
  1226.              ;
  1227.  
  1228. But this does not help, because Bison does not realize that the two
  1229. actions are identical.  (Bison never tries to understand the C code in
  1230. an action.)
  1231.  
  1232.    If the grammar is such that a declaration can be distinguished from
  1233. a statement by the first token (which is true in C), then one solution
  1234. which does work is to put the action after the open-brace, like this:
  1235.  
  1236.      compound: '{' { prepare_for_local_variables (); }
  1237.                declarations statements '}'
  1238.              | '{' statements '}'
  1239.              ;
  1240.  
  1241. Now the first token of the following declaration or statement, which
  1242. would in any case tell Bison which rule to use, can still do so.
  1243.  
  1244.    Another solution is to bury the action inside a nonterminal symbol
  1245. which serves as a subroutine:
  1246.  
  1247.      subroutine: /* empty */
  1248.                { prepare_for_local_variables (); }
  1249.              ;
  1250.  
  1251.      
  1252.      compound: subroutine
  1253.                '{' declarations statements '}'
  1254.              | subroutine
  1255.                '{' statements '}'
  1256.              ;
  1257.  
  1258. Now Bison can execute the action in the rule for `subroutine' without
  1259. deciding which rule for `compound' it will eventually use.  Note that
  1260. the action is now at the end of its rule.  Any mid-rule action can be
  1261. converted to an end-of-rule action in this way, and this is what Bison
  1262. actually does to implement mid-rule actions.
  1263.  
  1264. 
  1265. File: bison.info,  Node: Declarations,  Next: Multiple Parsers,  Prev: Semantics,  Up: Grammar File
  1266.  
  1267. Bison Declarations
  1268. ==================
  1269.  
  1270.    The "Bison declarations" section of a Bison grammar defines the
  1271. symbols used in formulating the grammar and the data types of semantic
  1272. values.  *Note Symbols::.
  1273.  
  1274.    All token type names (but not single-character literal tokens such
  1275. as `'+'' and `'*'') must be declared.  Nonterminal symbols must be
  1276. declared if you need to specify which data type to use for the semantic
  1277. value (*note Multiple Types::.).
  1278.  
  1279.    The first rule in the file also specifies the start symbol, by
  1280. default.  If you want some other symbol to be the start symbol, you
  1281. must declare it explicitly (*note Language and Grammar::.).
  1282.  
  1283. * Menu:
  1284.  
  1285. * Token Decl::       Declaring terminal symbols.
  1286. * Precedence Decl::  Declaring terminals with precedence and associativity.
  1287. * Union Decl::       Declaring the set of all semantic value types.
  1288. * Type Decl::        Declaring the choice of type for a nonterminal symbol.
  1289. * Expect Decl::      Suppressing warnings about shift/reduce conflicts.
  1290. * Start Decl::       Specifying the start symbol.
  1291. * Pure Decl::        Requesting a reentrant parser.
  1292. * Decl Summary::     Table of all Bison declarations.
  1293.  
  1294. 
  1295. File: bison.info,  Node: Token Decl,  Next: Precedence Decl,  Prev: Declarations,  Up: Declarations
  1296.  
  1297. Token Type Names
  1298. ----------------
  1299.  
  1300.    The basic way to declare a token type name (terminal symbol) is as
  1301. follows:
  1302.  
  1303.      %token NAME
  1304.  
  1305.    Bison will convert this into a `#define' directive in the parser,
  1306. so that the function `yylex' (if it is in this file) can use the name
  1307. NAME to stand for this token type's code.
  1308.  
  1309.    Alternatively you can use `%left', `%right', or `%nonassoc' instead
  1310. of `%token', if you wish to specify precedence.  *Note Precedence
  1311. Decl::.
  1312.  
  1313.    You can explicitly specify the numeric code for a token type by
  1314. appending an integer value in the field immediately following the
  1315. token name:
  1316.  
  1317.      %token NUM 300
  1318.  
  1319. It is generally best, however, to let Bison choose the numeric codes
  1320. for all token types.  Bison will automatically select codes that don't
  1321. conflict with each other or with ASCII characters.
  1322.  
  1323.    In the event that the stack type is a union, you must augment the
  1324. `%token' or other token declaration to include the data type
  1325. alternative delimited by angle-brackets (*note Multiple Types::.).
  1326.  
  1327.    For example:
  1328.  
  1329.      %union {              /* define stack type */
  1330.        double val;
  1331.        symrec *tptr;
  1332.      }
  1333.      %token <val> NUM      /* define token NUM and its type */
  1334.  
  1335. 
  1336. File: bison.info,  Node: Precedence Decl,  Next: Union Decl,  Prev: Token Decl,  Up: Declarations
  1337.  
  1338. Operator Precedence
  1339. -------------------
  1340.  
  1341.    Use the `%left', `%right' or `%nonassoc' declaration to declare a
  1342. token and specify its precedence and associativity, all at once. 
  1343. These are called "precedence declarations".  *Note Precedence::, for
  1344. general information on operator precedence.
  1345.  
  1346.    The syntax of a precedence declaration is the same as that of
  1347. `%token': either
  1348.  
  1349.      %left SYMBOLS...
  1350.  
  1351. or
  1352.  
  1353.      %left <TYPE> SYMBOLS...
  1354.  
  1355.    And indeed any of these declarations serves the purposes of
  1356. `%token'.  But in addition, they specify the associativity and
  1357. relative precedence for all the SYMBOLS:
  1358.  
  1359.    * The associativity of an operator OP determines how repeated uses
  1360.      of the operator nest: whether `X OP Y OP Z' is parsed by grouping
  1361.      X with Y first or by grouping Y with Z first.  `%left' specifies
  1362.      left-associativity (grouping X with Y first) and `%right'
  1363.      specifies right-associativity (grouping Y with Z first). 
  1364.      `%nonassoc' specifies no associativity, which means that `X OP Y
  1365.      OP Z' is considered a syntax error.
  1366.  
  1367.    * The precedence of an operator determines how it nests with other
  1368.      operators.  All the tokens declared in a single precedence
  1369.      declaration have equal precedence and nest together according to
  1370.      their associativity.  When two tokens declared in different
  1371.      precedence declarations associate, the one declared later has the
  1372.      higher precedence and is grouped first.
  1373.  
  1374. 
  1375. File: bison.info,  Node: Union Decl,  Next: Type Decl,  Prev: Precedence Decl,  Up: Declarations
  1376.  
  1377. The Collection of Value Types
  1378. -----------------------------
  1379.  
  1380.    The `%union' declaration specifies the entire collection of possible
  1381. data types for semantic values.  The keyword `%union' is followed by a
  1382. pair of braces containing the same thing that goes inside a `union' in
  1383. C.
  1384.  
  1385.    For example:
  1386.  
  1387.      %union {
  1388.        double val;
  1389.        symrec *tptr;
  1390.      }
  1391.  
  1392. This says that the two alternative types are `double' and `symrec *'. 
  1393. They are given names `val' and `tptr'; these names are used in the
  1394. `%token' and `%type' declarations to pick one of the types for a
  1395. terminal or nonterminal symbol (*note Type Decl::.).
  1396.  
  1397.    Note that, unlike making a `union' declaration in C, you do not
  1398. write a semicolon after the closing brace.
  1399.  
  1400.